import json
import os.path
import time
import threading
from libs.comps.common.component import manager , TComponentManager , TComponent
from libs.utils.tdb_utils import TTDB
class TCompKV( TComponent):
    def __init__(self, _manager):
        super().__init__(_manager)
        self.buckets={}
        self.valueChanged = False
    @property
    def bufferFileName(self):
        return self.compSettings['bufferFileName']
    @property
    def tdbSettings(self):
        res =None
        try:
            if 'tdbSettings' in self.compSettings.keys():
                res = self.compSettings['tdbSettings']
        except Exception as er:
            self.manager.log(self ,er)
        return res
    def setValue(self , bucketCode , devId , varId , value):
        try:
            if bucketCode not in self.buckets.keys():
                self.buckets[bucketCode]={}
            bucket = self.buckets[bucketCode]
            valueKey = f"vk_{devId}_{varId}"
            old = {}
            if valueKey in bucket.keys():
                old ={
                    "v": bucket[valueKey]['v'],
                    "t": bucket[valueKey]['t']
                }
            bucket[valueKey]={
                "v":value ,
                "t":time.time() ,
                "o": old
            }
            self.valueChanged = True
            self.save2DB( devId , varId , value)
        except Exception as er:
            self.manager.log(self , er)
    def save2DB(self , devId , varId , value):
        res = None
        try:
            measement = f"dev_{devId}"
            tags = f"vid={varId}"
            values = f"v={value}"
            dataStr = f"{measement},{tags} {values}"
            res = TTDB.write2TDB(
                host=self.tdbSettings['host'] ,
                port=self.tdbSettings['port'] ,
                token=self.tdbSettings['token'] ,
                db=self.tdbSettings['db'] ,
                datapointStr= dataStr
            )
        except Exception as er:
            self.manager.log(self , er)
        return res
    def saveBuffer(self):
        try:
            if self.valueChanged :
                self.valueChanged = False
                content = json.dumps(self.buckets , ensure_ascii=False)
                with open(self.bufferFileName , 'w' , encoding='utf-8') as f :
                    f.write(content)
        except Exception as er:
            self.manager.log(self , er)
    def serviceHandler(self):
        try:
            super().serviceHandler()
            while self.running:
                time.sleep(60)
                self.saveBuffer()
        except Exception as erBrfore:
            self.manager.log(self, erBrfore)
    def beforeStartService(self):
        try:
            super().beforeStartService()
            bufferPath = os.path.dirname(self.bufferFileName)
            if not os.path.exists(bufferPath):
                os.makedirs(bufferPath, 0x777)
        except Exception as er:
            self.manager.log(self, er)
    def startService(self):
        try:
            if not self.running:
                try:
                    self.beforeStartService()
                except Exception as erBrfore:
                    self.manager.log(self, erBrfore)
                self.serviceThread = threading.Thread(target=self.serviceHandler , daemon=True)
                self.running = True
                self.serviceThread.start()
        except Exception as er:
            self.manager.log(self, er)
    def stopService(self):
        try:
            self.running = False
        except Exception as er:
            self.manager.log(self, er)
manager.registCompType("TCompKV", TCompKV)
